<?php
	require_once('image.php');
	require_once('DAO.php');
	
	# Le 'Data Access Object' d'un ensemble images
	class ImageDAO extends DAO {
		
		# Retourne le nombre d'images référencées dans le DAO
		function size() {
			$s = $this->db->query('SELECT COUNT(id) as count FROM image');
			$s = $s->fetch(PDO::FETCH_OBJ);
			return $s->count;
		}
		
		# Retourne un objet image correspondant à l'identifiant
		function getImage($imgId) {
			$s = $this->db->prepare('SELECT * FROM image WHERE id = :iid');
			$s->bindValue(':iid', $imgId, PDO::PARAM_INT);
			$s->execute();
			if ($s) {
				# Verifie que cet identifiant est correct
				if(!($imgId >= 1 AND $imgId <= $this->size())) {
					debug_print_backtrace();
					die('<h1>Erreur dans ImageDAO.getImage: imgId='.$imgId.' incorrect</h1>');
				}
				$s = $s->fetch(PDO::FETCH_OBJ);
				if (!preg_match('#^http:\/\/#', $s->path))
					return new Image(self::urlPath.$s->path,$imgId, $s->comment, $s->category, $s->path, $s->like, $s->unlike);
				else
					return new Image($s->path,$imgId, $s->comment, $s->category, $s->path, $s->like, $s->unlike);
			} else {
				echo 'Erreur dans getImage. id = '.$imgId.'<br />';
				echo '<pre>'; print_r($this->db->errorInfo()); echo '</pre>';
				return null;
			}
		}
		
		function getImageByCat($categorie, $imgId=null) {
			if( !is_null($imgId) ) {
				$s = $this->db->prepare('SELECT * FROM image WHERE category = :categorie AND id = :id');
				$s->bindValue(':id', $imgId);
			} else {
				$s = $this->db->prepare('SELECT * FROM image WHERE category = :categorie ORDER BY id ASC');
			}
			$s->bindValue(':categorie', $categorie);
			$s->execute();
			if ($s) {
				$s = $s->fetch(PDO::FETCH_OBJ);
				if (!preg_match('#^http:\/\/#', $s->path))
					return new Image(self::urlPath.$s->path,$s->id, $s->comment, $s->category, $s->path, $s->like, $s->unlike);
				else
					return new Image($s->path,$s->id, $s->comment, $s->category, $s->path, $s->like, $s->unlike);
			} else {
				debug($this->db->errorInfo());
				return null;
			}
		}

		function getCategories() {
			$s = $this->db->query('SELECT DISTINCT(category) as categorie FROM image ORDER BY category');
			$s->execute();
			return $s->fetchAll(PDO::FETCH_OBJ);
		}
		
		# Retourne une image au hazard
		function getRandomImage() {
			$id = rand(1, $this->size());
			$s = $this->db->prepare('SELECT * FROM image WHERE id = :iid');
			$s->bindValue(':iid', $id, PDO::PARAM_INT);
			$s->execute();
			if ($s) {
				$s = $s->fetch(PDO::FETCH_OBJ);
				if (!preg_match('#^http:\/\/#', $s->path))
					return new Image(self::urlPath.$s->path,$s->id, $s->comment, $s->category, $s->path, $s->like, $s->unlike);
				else
					return new Image($s->path,$s->id, $s->comment, $s->category, $s->path, $s->like, $s->unlike);
			} else
				return null;
		}
		
		# Retourne l'objet de la premiere image
		function getFirstImage() {
			return $this->getImage(1);
		}
		
		# Retourne l'image suivante d'une image
		function getNextImage($idStart, $categorie=null) {
			if( !empty($categorie) ){
				$img = $this->getImageByCat($categorie, $idStart);
			} else {
				$img = $this->getImage($idStart);
			}
			return $img;
		}
		
		# Retourne l'image précédente d'une image
		function getPrevImage($idStart, $categorie=null) {
			if( !empty($categorie) ) {
				$img = $this->getImageByCat($categorie, $idStart);
			} else {
				$img = $this->getImage($idStart);
			}
			return $img;
		}
		
		# saute en avant ou en arrière de $nb images
		# Retourne la nouvelle image
		function jumpToImage($idStart, $nb) {
			if ($idStart+$nb < $this->size())
				$img = $this->getImage($idStart+$nb);
			return $img;
		}
		
		# Retourne la liste des images consécutives à partir d'une image
		function getImageList($idStart, $nb) {
			# Verifie que le nombre d'image est non nul
			if (!$nb > 0) {
				debug_print_backtrace();
				trigger_error("Erreur dans ImageDAO.getImageList: nombre d'images nul");
			}
			$idStart = $idStart > 0 ? $idStart : 1;
			$max = $idStart+$nb;
			$res = array();
			while ($idStart < $this->size() && $idStart < $max) {
				$res[] = $this->getImage($idStart);
				$idStart++;
			}
			return $res;
		}
		
		# Enregistre l'image, fait un update du commentaire et de la catégorie si elle existe déjà
		function save(Image $img) {
			$exists = $img->getId();
			if (is_null($exists))
			{
				$query = 'INSERT INTO image (path, category, comment, `like`, unlike) VALUES (:path, :category, :comment, 0, 0)';
			}
			else
			{
				$query = "UPDATE image SET comment=:comment, category=:category, `like`=:like, unlike=:unlike WHERE id=:id";
			}
			$stmt = $this->db->prepare($query);
			$stmt->bindValue(':category', $img->getCategory(), PDO::PARAM_STR);
			$stmt->bindValue(':comment', $img->getComment(), PDO::PARAM_STR);
			if (is_null($exists))
			{
				$stmt->bindValue(':path', $img->getPath());
			}
			else
			{
				$stmt->bindValue(':id', $img->getId());
				$stmt->bindValue(':like', $img->getLike(), PDO::PARAM_INT);
				$stmt->bindValue(':unlike', $img->getUnlike(), PDO::PARAM_INT);
			}
			
			$stmt->execute();
		}

		function getPreviousId($idImg, $categorie) {
			if( empty($categorie) ) {
				if( $idImg <= 1 ) {
					$idImg = 2;
				}
				return $idImg-1;
			}
			$s = $this->db->prepare('SELECT id FROM image WHERE category = :categorie AND id < :idImg ORDER BY id DESC LIMIT 1');
			$s->bindValue(':categorie', $categorie);
			$s->bindValue(':idImg', $idImg);
			$s->execute();

			$s = $s->fetch(PDO::FETCH_OBJ);
			return (!is_object($s)) ? $idImg : $s->id;
		}

		function getNextId($idImg, $categorie) {
			if( empty($categorie) ) {
				if ($idImg < $this->size()) {
					$idImg = $idImg+1;
				}
				return $idImg;
			}
			$s = $this->db->prepare('SELECT id FROM image WHERE category = :categorie AND id > :idImg LIMIT 1');
			$s->bindValue(':categorie', $categorie);
			$s->bindValue(':idImg', $idImg);
			$s->execute();

			$s = $s->fetch(PDO::FETCH_OBJ);
			return (!is_object($s)) ? $idImg : $s->id;
		}
		
		function getLastInsertId() {
			return $this->db->lastInsertId();
		}
		
		function getImagesWithoutAlbum() {
			$stmt = $this->db->query('SELECT * FROM image
										WHERE id NOT IN (SELECT id_image FROM album_image)');
			$imgs = $stmt->fetchAll(PDO::FETCH_OBJ);
			$ret = array();
			foreach ($imgs as $i) {
				if (!preg_match('#^http:\/\/#', $i->path))
					$ret[] = new Image(self::urlPath.$i->path,$i->id, $i->comment, $i->category, $i->path, $i->like, $i->unlike);
				else
					$ret[] = new Image($i->path,$i->id, $i->comment, $i->category, $i->path, $i->like, $i->unlike);
			}
			return $ret;
		}
	}
	
	
	?>